package sub

import (
	"DmsRocketMQ/common"
	"context"
	"fmt"
	"github.com/apache/rocketmq-client-go/v2"
	"github.com/apache/rocketmq-client-go/v2/consumer"
	"github.com/apache/rocketmq-client-go/v2/primitive"
	"github.com/pkg/errors"
)

func GetOrderlyConsumer(config common.Config) (rocketmq.PushConsumer, error) {
	c, err := rocketmq.NewPushConsumer(
		consumer.WithGroupName(config.Group),
		consumer.WithNsResolver(primitive.NewPassthroughResolver(config.Host)),
		consumer.WithRetry(2),
		consumer.WithConsumerOrder(true),
	)
	if err != nil {
		return nil, errors.Wrap(err, "ERR: fail to init a consumer")
	}
	return c, nil
}

func SubscribeOrderlyMessage(c rocketmq.PushConsumer, topic string) error {
	err := c.Subscribe(topic, consumer.MessageSelector{}, func(ctx context.Context,
		msgs ...*primitive.MessageExt) (consumer.ConsumeResult, error) {
		orderlyCtx, _ := primitive.GetOrderlyCtx(ctx)
		fmt.Printf("orderly context : %v",orderlyCtx)
		//遍历消费消息
		for i := range msgs {
			fmt.Printf("rocketmq message: %v \n", msgs[i])
		}

		return consumer.ConsumeSuccess, nil
	})
	if err != nil {
		return errors.Wrap(err, "ERR: fail to subscribe message")
	}
	err = c.Start()
	if err != nil {
		return errors.Wrap(err, "ERR: fail to start consumer")
	}
	return nil
}
